/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package su.samlib.informer.database.controllers;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import su.samlib.informer.database.model.Author;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import su.samlib.informer.database.controllers.exceptions.IllegalOrphanException;
import su.samlib.informer.database.controllers.exceptions.NonexistentEntityException;
import su.samlib.informer.database.model.Library;

/**
 *
 * @author rikland
 */
public class LibraryJpaController implements Serializable {

    public LibraryJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Library library) {
        if (library.getAuthorList() == null) {
            library.setAuthorList(new ArrayList<Author>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Author> attachedAuthorList = new ArrayList<Author>();
            for (Author authorListAuthorToAttach : library.getAuthorList()) {
                authorListAuthorToAttach = em.getReference(authorListAuthorToAttach.getClass(), authorListAuthorToAttach.getAuthorId());
                attachedAuthorList.add(authorListAuthorToAttach);
            }
            library.setAuthorList(attachedAuthorList);
            em.persist(library);
            for (Author authorListAuthor : library.getAuthorList()) {
                Library oldLibraryIdOfAuthorListAuthor = authorListAuthor.getLibraryId();
                authorListAuthor.setLibraryId(library);
                authorListAuthor = em.merge(authorListAuthor);
                if (oldLibraryIdOfAuthorListAuthor != null) {
                    oldLibraryIdOfAuthorListAuthor.getAuthorList().remove(authorListAuthor);
                    oldLibraryIdOfAuthorListAuthor = em.merge(oldLibraryIdOfAuthorListAuthor);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Library library) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Library persistentLibrary = em.find(Library.class, library.getLibraryId());
            List<Author> authorListOld = persistentLibrary.getAuthorList();
            List<Author> authorListNew = library.getAuthorList();
            List<String> illegalOrphanMessages = null;
            for (Author authorListOldAuthor : authorListOld) {
                if (!authorListNew.contains(authorListOldAuthor)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Author " + authorListOldAuthor + " since its libraryId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Author> attachedAuthorListNew = new ArrayList<Author>();
            for (Author authorListNewAuthorToAttach : authorListNew) {
                authorListNewAuthorToAttach = em.getReference(authorListNewAuthorToAttach.getClass(), authorListNewAuthorToAttach.getAuthorId());
                attachedAuthorListNew.add(authorListNewAuthorToAttach);
            }
            authorListNew = attachedAuthorListNew;
            library.setAuthorList(authorListNew);
            library = em.merge(library);
            for (Author authorListNewAuthor : authorListNew) {
                if (!authorListOld.contains(authorListNewAuthor)) {
                    Library oldLibraryIdOfAuthorListNewAuthor = authorListNewAuthor.getLibraryId();
                    authorListNewAuthor.setLibraryId(library);
                    authorListNewAuthor = em.merge(authorListNewAuthor);
                    if (oldLibraryIdOfAuthorListNewAuthor != null && !oldLibraryIdOfAuthorListNewAuthor.equals(library)) {
                        oldLibraryIdOfAuthorListNewAuthor.getAuthorList().remove(authorListNewAuthor);
                        oldLibraryIdOfAuthorListNewAuthor = em.merge(oldLibraryIdOfAuthorListNewAuthor);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = library.getLibraryId();
                if (findLibrary(id) == null) {
                    throw new NonexistentEntityException("The library with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Library library;
            try {
                library = em.getReference(Library.class, id);
                library.getLibraryId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The library with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Author> authorListOrphanCheck = library.getAuthorList();
            for (Author authorListOrphanCheckAuthor : authorListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Library (" + library + ") cannot be destroyed since the Author " + authorListOrphanCheckAuthor + " in its authorList field has a non-nullable libraryId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(library);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Library> findLibraryEntities() {
        return findLibraryEntities(true, -1, -1);
    }

    public List<Library> findLibraryEntities(int maxResults, int firstResult) {
        return findLibraryEntities(false, maxResults, firstResult);
    }

    private List<Library> findLibraryEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Library.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Library findLibrary(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Library.class, id);
        } finally {
            em.close();
        }
    }

    public int getLibraryCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Library> rt = cq.from(Library.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
